package com.app.exception;

import com.app.constants.AspectSequenceConstant;
import com.app.response.BaseResponse;
import com.app.response.ResponseCode;
import com.app.web.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * @author ZhengJunJie
 * @date 2019/12/31 18:45
 */
@ControllerAdvice
@Slf4j
@Order(AspectSequenceConstant.ORDER_GLOBAL_EXCEPTION_LOG_OUT)
public class GlobalExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public <T extends Serializable> BaseResponse<T> handle(HttpServletRequest request, Exception e) {
        String errorMessage = e.getMessage();
        logError(request, errorMessage, e);
        if (e instanceof SystemException) {
            String code = ResponseCode.SYSTEM_ERROR.getCode();
            SystemException exception = (SystemException) e;
            String errorCode = exception.getCode();
            if (null != errorCode) {
                code = errorCode;
            }
            return BaseResponse.fail(code, errorMessage);
        }
        return BaseResponse.fail(ResponseCode.SYSTEM_ERROR, e.getMessage() == null ? "服务器内部错误" : errorMessage);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public <T extends Serializable> BaseResponse<T> handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return BaseResponse.fail(ResponseCode.SYSTEM_ERROR, fieldError.getDefaultMessage());
    }

    private void logError(HttpServletRequest request, String message, Exception e) {
        log.error(structureErrorMessage(request, message, e), e);
    }

    private String structureErrorMessage(HttpServletRequest request, String message, Exception e) {
        String errorMessage = "请求地址:%s | 请求内容:%s | 异常信息:%s | 异常堆栈:%s";
        String requestContent = StringUtils.EMPTY;

        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            BodyReaderHttpServletRequestWrapper contentCachingRequestWrapper = (BodyReaderHttpServletRequestWrapper) request;
            requestContent = StringUtils.toEncodedString(contentCachingRequestWrapper.getBody().getBytes(), StandardCharsets.UTF_8);
        }
        ExceptionUtils.getStackTrace(e);

        return String.format(errorMessage, request.getRequestURL(), requestContent, message, ExceptionUtils.getStackTrace(e));
    }
}